//! @Author: DengLibin
//! @Date: Create in 2025-03-19 10:58:56
//! @Description: excel操作

use calamine::{open_workbook, Error, RangeDeserializerBuilder, Reader, Xlsx};
use serde::Serialize;

pub fn example() -> Result<(), Error> {
    let path = format!("{}/tests/temperature.xlsx", env!("CARGO_MANIFEST_DIR"));
    let mut workbook: Xlsx<_> = open_workbook(path)?;
    let range = workbook.worksheet_range("Sheet1")?;

    let mut iter = RangeDeserializerBuilder::new().from_range(&range)?;

    if let Some(result) = iter.next() {
        let (label, value): (String, f64) = result?;
        assert_eq!(label, "celsius");
        assert_eq!(value, 22.2222);
        Ok(())
    } else {
        Err(From::from("expected at least one record but got none"))
    }
}

#[derive(Debug, Serialize)]
pub struct ExcelModel {
    pub sheets: Vec<ExcelSheet>,
}

#[derive(Debug, Serialize)]
pub struct ExcelSheet {
    pub sheet_name: String,     //sheet名称
    pub rows: Vec<Vec<String>>, //数据
}

/// @Author: DengLibin
/// @Date: Create in 2025-03-19 11:03:35
/// @Description: 读取excel xlsx格式
pub fn read_xlsx(xlsx_path: &str) -> Result<ExcelModel, Box<dyn std::error::Error>> {
    let mut sheets: Vec<ExcelSheet> = vec![];

    let mut workbook: Xlsx<_> = open_workbook(xlsx_path)?;
    let sheet_names = workbook.sheet_names();
    for sheet_name in sheet_names.iter() {
        let mut sheet = ExcelSheet {
            sheet_name: sheet_name.to_string(),
            rows: vec![],
        };

        let range = workbook.worksheet_range(&sheet_name)?;
        for row in range.rows() {
            let row_vec = row
                .iter()
                .map(|cell| cell.to_string())
                .collect::<Vec<String>>();
            sheet.rows.push(row_vec);
        }
        sheets.push(sheet);
    }

    Ok(ExcelModel { sheets })
}
